<template>
  <div class="personnel-entry-exit-review bg-background text-foreground p-4">
    <h2 class="text-2xl font-bold mb-4">预约审核</h2>

    <!-- Search Bar -->
    <div class="bg-card text-card-foreground p-4 mb-4 rounded shadow">
      <QueryForm :model="search" :formItems="formItems" @search="searchApplications" @reset="resetSearch" />
    </div>


    <div class="mb-4 space-x-2">
      <el-button @click="exportData(planData, '预约审核', selectedIds)">导出</el-button>

    </div>


    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <el-table v-loading="loading" :data="displayedApplications" @selection-change="handleSelectionChange"
        style="width: 100%" ref="table" align="center" class="data-table" :header-cell-style="headerCellStyle"
        :row-key="rowKey">
        <!-- <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column> -->
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LICENSE_PLATE" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_MATERIAL_NAME" label="危化品名称" header-align="center"
          align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_MATERIAL_TYPE" label="危化品类型" header-align="center" align="center">

        </el-table-column>
        <el-table-column prop="AUDITOR" label="审核人" header-align="center" align="center"></el-table-column>
        <el-table-column prop="AUDIT_TIME" label="审核日期" header-align="center" align="center">
          <template #default="scope">
            <div>{{ scope.row.AUDIT_TIME != null ? dayjs(scope.row.AUDIT_TIME).format('YYYY-MM-DD HH:mm:ss') : '' }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="STATE" label="状态" header-align="center" align="center">
          <template #default="scope">
            <div :class="getStatusClass(scope.row.STATE)">
              {{ scope.row.STATE == 0 ? '待审核' : scope.row.STATE == 1 ? '通过' : '未通过' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">

            <el-button v-if="scope.row.STATE == 0" type="primary" size="small" @click="reviewApplication(scope.row)"
              link>审核</el-button>
            <el-button v-else type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->

    <Pagination v-if="applications.length" :tableData="applications" @alltabledata="alltabledata" />
    <!-- Review Dialog -->
    <el-dialog class="dialog-from" v-model="isReviewDialogOpen" title="审核" width="650" destroy-on-close align-center>
      <form>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>基本信息</span>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <div><strong>系统单号：</strong>{{ reviewForm.SYSTEM_CODE }}</div>
          <div><strong>车牌号码：</strong>{{ reviewForm.LICENSE_PLATE }}</div>
          <div><strong>车辆类型：</strong>{{ reviewForm.HAZARDOUS_VEHICLES_TYPE }}</div>
          <div><strong>危化品名称：</strong>{{ reviewForm.HAZARDOUS_MATERIAL_NAME }}</div>
          <div><strong>危化品类别：</strong>{{ reviewForm.HAZARDOUS_MATERIAL_TYPE }}</div>
          <div><strong>数量(KG)：</strong>{{ reviewForm.WEIGHT }}</div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>驾驶员信息</span>
        </div>
        <div class="grid grid-cols-3 gap-4">
          <div><strong>驾驶员姓名：</strong>{{ reviewForm.DRIVER_NAME }}</div>
          <div><strong>证件号码：</strong>{{ reviewForm.DRIVER_ID_NUMBER }}</div>
          <div><strong>联系方式：</strong>{{ reviewForm.DRIVER_PHONE }}</div>
          <div><strong>驾驶证：</strong>
            <span v-for="item in imgdata" :key="item">
              <el-image style="width: 100px; height: 100px" lazy :src="item" :zoom-rate="1.2" :max-scale="7"
                :min-scale="0.2" :initial-index="0" fit="cover" />
            </span>
          </div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>申请信息</span>
        </div>
        <div class="grid grid-cols-2 gap-4">
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">入场时间：</label>
            <input type="datetime-local" :disabled="isViewDialogOpen" v-model="reservationreviewForm.IN_AT"
              class="input" />
          </div>
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">出场时间：</label>
            <input type="datetime-local" :disabled="isViewDialogOpen" v-model="reservationreviewForm.EXIT_AT"
              class="input" />
          </div>
          <div>
            <label for="licensePlate" class="block text-sm font-medium text-muted-foreground">授权区域：</label>
            <el-checkbox-group :disabled="isViewDialogOpen" v-model="reservationreviewForm.AUTHORITY_AREA"
              style="width: 500px;">
              <el-checkbox v-for="(item, index
              ) in getchechedarr" :key="index" :value="item.ID">{{ item.PARKING_NAME + '/' + item.
                PARKING_AREA }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div class="tablename">
          <div
            style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
          </div>
          <span>其他信息</span>
        </div>
        <div><strong>备注：</strong>{{ reviewForm.stamp }}</div>
        <div class="mt-6 flex justify-end space-x-2">
          <button @click.prevent="submitReview('1')" class="btn btn-primary">审核通过</button>
          <button @click.prevent='submitReview("2")' class="btn btn-primary">审核拒绝</button>
          <button type="button" @click="closeReviewDialog" class=" btn btn-secondary">取消</button>
        </div>
      </form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import axios from 'axios'

const { proxy } = getCurrentInstance()

import { dayjs } from "element-plus"

const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/hazardous-vehicle-review'
})
const reservationreviewForm = ref({
  ID: '',
  IN_AT: "",
  EXIT_AT: "",
  AUTHORITY_AREA: [],
  STATE: ''
})
const search = ref({
  LICENSE_PLATE: "",
  DRIVER_NAME: "",
  STATE: "",
})
const formItems = ref([
  {
    label: '车牌号码：',
    model: 'LICENSE_PLATE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },

  {
    label: '审核状态：',
    model: 'STATE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '待审核', value: '0' },
      { label: '通过', value: '1' },
      { label: '未通过', value: '2' },
    ],
  },
])
const applications = ref([])
const isReviewDialogOpen = ref(false)
const isViewDialogOpen = ref(false)
const reviewForm = ref({

})
const loading = ref(false)
const displayedPlanData = ref([])
const imgdata = ref([])

const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
}
const rowKey = (row) => row.ID // 设置行的唯一标识

const selectedIds = ref([])

const getchechedarr = ref([])



const displayedApplications = ref([])
const alltabledata = (data) => {
  displayedApplications.value = data

}
const searchApplications = async () => {
  try {
    displayedApplications.value = []
    const response = await axios.get(`${apiBaseUrl.value}/search`, { params: search.value })
    applications.value = response.data
  } catch (error) {
    console.error('搜索申请失败:', error)
    alert('搜索申请失败: ' + (error.response?.data?.message || error.message))
  }
}
const getcheched = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/area`)
    getchechedarr.value = response.data
  } catch (error) {
    console.error('失败:', error)
    alert('失败: ' + (error.response?.data?.message || error.message))
  }
}
const resetSearch = () => {
  search.value = {
    LICENSE_PLATE: '',
    DRIVER_NAME: '',
    STATE: '',
  }
  searchApplications()
}

const reviewApplication = async (application) => {

  reviewForm.value = {
    ...application
  }
  reservationreviewForm.value.ID = application.ID
  const response = await axios.get(`${apiBaseUrl.value}/download/${reviewForm.value.DRIVING_LICENSE}`)
  imgdata.value.push(response.data.url)
  isReviewDialogOpen.value = true
}

const closeReviewDialog = () => {
  isReviewDialogOpen.value = false
  imgdata.value = []
  reservationreviewForm.value = {
    ID: '',
    IN_AT: "",
    EXIT_AT: "",
    AUTHORITY_AREA: [],
    STATE: ''
  }
  isViewDialogOpen.value = false
}


const submitReview = async (item) => {
  reservationreviewForm.value.STATE = Number(item)
  try {
    await axios.put(`${apiBaseUrl.value}/${reservationreviewForm.value.ID}`, reservationreviewForm.value)
    alert('审核提交成功')

    closeReviewDialog()
    await searchApplications()
  } catch (error) {
    console.error('审核提交失败:', error)
    alert('审核提交失败: ' + (error.response?.data?.message || error.message))
  }
}

const viewDetails = (item) => {
  reviewForm.value = item
  reservationreviewForm.value = item
  reservationreviewForm.value.AUTHORITY_AREA = reservationreviewForm.value.AUTHORITY_AREA
  reservationreviewForm.value.IN_AT = dayjs(reservationreviewForm.value.IN_AT).format('YYYY-MM-DD HH:mm:ss')
  reservationreviewForm.value.EXIT_AT = dayjs(reservationreviewForm.value.EXIT_AT).format('YYYY-MM-DD HH:mm:ss')
  isReviewDialogOpen.value = true
  isViewDialogOpen.value = true
}




const getStatusClass = (status) => {
  const classMap = {
    '0': 'bg-yellow-100 text-yellow-800',
    '1': 'bg-green-100 text-green-800',
    '2': 'bg-red-100 text-red-800'
  }
  return `px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${classMap[status] || ''}`
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

onMounted(() => {
  searchApplications()
  getcheched()
})
</script>

<style scoped>
.input {
  @apply mt-1 block w-full rounded-md border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring;
}

.btn {
  @apply px-4 py-2 rounded-md font-medium focus:outline-none focus:ring-2 focus:ring-offset-2 transition duration-150 ease-in-out;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}

.tablename {
  display: flex;
  align-items: baseline;
  margin: 10px 0;
  font-weight: bold;
}
</style>
